using Autodesk.Revit.UI;
using RevitForge.ViewModels;
using ICSharpCode.AvalonEdit.Highlighting;
using System;
using System.ComponentModel;
using System.Windows.Controls;
using ICSharpCode.AvalonEdit.Editing;

namespace RevitForge.Views
{
    public partial class ScriptBotView : UserControl
    {
        public ScriptBotView(ExternalEvent externalEvent)
        {
            InitializeComponent();
            var viewModel = new ScriptBotViewModel(externalEvent);
            DataContext = viewModel;
            CodeEditor.Options.EnableHyperlinks = true;
            CodeEditor.Options.EnableEmailHyperlinks = true;
            // 设置代码内容
            CodeEditor.Text = viewModel.UserCode;

            bool isUpdatingText = false;
            // 监听文本变化事件处理
            CodeEditor.TextChanged += (s, e) =>
            {
                if (!isUpdatingText && DataContext is ScriptBotViewModel vm)
                {
                    vm.UserCode = CodeEditor.Text;
                }
            };

            // 监听ViewModel属性变化事件
            if (viewModel is INotifyPropertyChanged notifyPropertyChanged)
            {
                notifyPropertyChanged.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(ScriptBotViewModel.UserCode))
                    {
                        isUpdatingText = true;
                        try
                        {
                            // 保存当前光标位置和滚动位置
                            var caretOffset = CodeEditor.CaretOffset;
                            var scrollOffset = CodeEditor.VerticalOffset;

                            using (CodeEditor.Document.RunUpdate())
                            {
                                CodeEditor.Document.Text = viewModel.UserCode;
                            }

                            // 恢复光标位置和滚动位置
                            CodeEditor.CaretOffset = Math.Min(caretOffset, CodeEditor.Document.TextLength);
                            CodeEditor.ScrollToVerticalOffset(scrollOffset);
                        }
                        finally
                        {
                            isUpdatingText = false;
                        }
                    }
                };
            }
        }
    }
}
